<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'>
          <el-select v-model="searchData.business_type_id" placeholder="业务类型" clearable filterable>
            <el-option :value= row.id v-for="(row,i) in leaderlist" :label= row.desc :key= i >{{row.desc}}</el-option>
          </el-select>
        </div> 
        <div class='form-group-enquire'>
          <el-select v-model="searchData.sieve_source_name" placeholder="请选择筛料源" clearable filterable>
            <el-option :value= row.name v-for="row in statuslist" :label="row.name" :key= row.id >{{row.name}}</el-option>
          </el-select>
        </div>          
        <div class='form-group-enquire'>
          <el-select v-model="searchData.account_id" placeholder="充值账户" clearable filterable>
            <el-option :value= row.id v-for="row in rolelist" :label="'('+ row.id+')'+row.name" :key= row.id ><span style="float:left;color:#FF0000">({{row.id}})&nbsp;</span>{{row.name}}</el-option>
          </el-select>
        </div>    
        <div class='form-group-enquire'>
          <DatePicker type="daterange" placeholder="日期" style="width: 190px" :editable=false v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>
        </div>        
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg2' @click='downloadFile()'><img src="../../assets/images/peach-svg/export.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" 
        :stripe="stripe"
        @onSelectChange="onCheckChange"
        border="none"  
        :tableColumns="tableColumns" 
        :tableData="list" 
        :slotHeader="slotHeader" 
        :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size,pageSizes:[30, 50, 100,1000]}"  
        @onPageChange="onChangePageSize" 
        :footer-method="footerMethodFunc"
        resizable>
      </LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from '../../commons/staticName'
import bus from "../../commons/EventBus";
export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      stripe:false,       
      statuslist: [],
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        date:'',
        page_index:1,
        page_size:30,
        business_type_id:'',
        leader_name :"",
        sieve_source_name:""
      },
      versionsList:[{Id:-1,Name:'全部版本'},{Id:1,Name:'v1'},{Id:2,Name:'v2'}],
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      points_consume: 0,
      points_consume_account: 0,
      points_consume_gift: 0,
      profit: 0,
      task_nums: 0,
      task_nums_valid: 0,
      info:{},
      rolelist:[],
      selectRows:[],
      channelList:[],
      cityList:[],
      cityInfo:[-1],
      partnerList:[],
      ChannelList:[],
      QdsPartnerList:[],
      QdsPartnerObj:{},
      BusinessList:[],
      BusinessObj:{},
      cityObj:{},
      brandObj:{},
      brandObjCh:{},
      roles:[],
      leaders:[],
      roleList:{},
      rollist:[],
      leaderlist:[],
      eid:"",
      tableColumns:[
        { 
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "日期",
          field: "date",
          align: 'center',
        },
        {
          title: "业务类型",
          field: "business_type_desc",
          align: 'center',
        },
        {
          title: "筛源",
          field: "sieve_source_name",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.sieve_source_name==0){
                return [h("div",'-')]
              }else
              return [h("div",row.sieve_source_name)]
            }
          }
        },
        {
          title: "消耗积分",
          field: "points_consume",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume/10000)]
            }
          }
        },
        {
          title: "账号消耗",
          field: "points_consume_account",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_account==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_account/10000)]
            }
          }
        },
        {
          title: "赠送消耗",
          field: "points_consume_gift",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_gift==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_gift/10000)]
            }
          }
        },
        {
          title: "利润",
          field: "profit",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.profit==0){
                return [h("div",'-')]
              }else
              return [h("div",row.profit/10000)]
            }
          }
        },
        {
          title: "平台消耗积分",
          field: "profit2",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.profit==0){
                return [h("div",'-')]
              }else
              return [h("div",row.profit/10000)]
            }
          }
        },
         {
          title: "平台消耗充值",
          field: "profit3",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.profit==0){
                return [h("div",'-')]
              }else{
                let jifen = (row.profit * row.points_consume_account / row.points_consume)/10000
                jifen = (String(jifen).indexOf('.') + 1 > 0 && ( String(jifen).length - (String(jifen).indexOf('.') + 1) > 4)) ? parseFloat(jifen).toFixed(4) :jifen
               return [h("div",jifen)]
              }
            }
          }
        },
        {
          title: "平台消耗赠送",
          field: "profit4",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.profit==0){
                return [h("div",'-')]
              }else {
                  let jifen = (row.profit * row.points_consume_gift / row.points_consume)/10000
                  jifen = (String(jifen).indexOf('.') + 1 > 0 && ( String(jifen).length - (String(jifen).indexOf('.') + 1) > 4)) ? parseFloat(jifen).toFixed(4) :jifen
                return [h("div",jifen)]
              }
              
            }
          }
        },
        {
          title: "任务数",
          field: "task_nums",
          align: 'center',         
        },
        {
          title: "有效数",
          field: "task_nums_valid",
          align: 'center',
        },
         {
          title: "操作人",
          field: "leader_name",
          align: 'center',
        },
      ],
      format: {  
        account:{
          labelName: "账号",
          labelType: "text",      
          placeholder:"请输入账号"
        },
        passwd:{
          labelName: "密码",
          labelType: "password",     
          placeholder:"请输入密码"          
        },
        role_id:{
          labelName: "用户角色",
          labelType: "select",
          labelValue:[],          
          placeholder:"请选择角色" 
        },
        leader_id:{
          labelName: "代理商",
          labelType: "select",
          labelValue:[],          
          placeholder:"请选择代理商"  
        }                
      },       
      ruleValidate: {
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        await this.getList();
        await this.initSearchData();
      }

    },
    onCheckChange(rows){
        this.selectRows = [];
        this.selectRows = rows;
    },
    //导出
    async downloadFile() {
      // utils.showLoading("正在生成中")
      let new_ids=""
      if(this.selectRows.records!=undefined){
        //导出值用id|id形式拼接
        this.selectRows.records.forEach(item => {
          new_ids+='|'+item.id
        });
        if(new_ids!=''){
          new_ids=new_ids.substring(1)
        }
        let res = await this.RequestPost("export_list",{"ids":new_ids});
        console.log(res);
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
        }
        window.open(ACDN+res.data)
      }else{
         utils.shadowModel(
          {
            "icon":require('../../assets/images/Frame 427318277.svg'),            
            "modalContent":"请选择一项 ",
            "title":"提交失败"
          });
      }
      
    }, 
    //业务类型下拉框接口
    async initSearchData(){
      let res2 = await Request.post("customer/user", "query_list");
      this.rolelist=[]
      if(res2.code==0 && res2.data != null){
        res2.data.list.forEach((item) => {
          this.rolelist.push({id:item.id,name:item.account});
        })  
      }
      let res = await Request.post('customer/businessType','queryTypes_list')
      let data = res.data
      if(res.code==0 && data.length != 0){
        data.forEach(res =>{
          this.leaderlist.push(res)
        })
      } 
      let res23 = await Request.post("customer/sieveConfig","query_list")//筛料源接口
      let label=''
      if(res23.code==0 && res23.data.length != 0){
        res23.data.list.forEach(res23 =>{
          label=res23.name=="sjb"?"数据吧":res23.name=='internal'?'自研':res23.name
          this.statuslist.push({id:res23.id,name:label+"("+res23.alias+")"})
        })
      }
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData);
      console.log(res,'srea');     
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) this.list = res.data.list;
        this.totalCnt = res.data.total
        this.points_consume = res.data.all.points_consume
        this.points_consume_account = res.data.all.points_consume_account
        this.points_consume_gift = res.data.all.points_consume_gift
        this.profit = res.data.all.profit
        this.task_nums = res.data.all.task_nums
        this.task_nums_valid = res.data.all.task_nums_valid
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },    
    //添加 编辑用户
    async editInfo(row,type) {
      this.eid = row.id
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "添加用户";
        info = {
          account:"",          
          passwd:"",
          role_id:"",
          leader_id:"",
        };
      }else if(this.handleType==2){
        console.log('1');
        if (row.status > 1){
          this.format.Status.labelDisabled = true
        }
        title = "编辑用户";
        info = {
          account:row.account,    
          passwd:row.passwd,
          leader_id:row.leader_id,      
          role_id:row.role_id,         
        };
      }else if(this.handleType==3){
        this.format.account.labelDisabled = true
        title = "修改密码";
        info = {
          account:row.account,    
          passwd:"",      
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
      this.getList()
    },      
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      console.log(postData,'upda');
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '添加成功！';  
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '编辑成功！';     
        postData = {"id":this.eid,"account":postData.account,"role_id":postData.role_id};
        delete postData.PurchaseType
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'resetPasswd_item';
        tipText = '修改密码成功';
        postData = {"id":this.eid,"passwd":postData.passwd};
      }    
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        utils.showTip(tipText);
      }
      utils.hideLoading();
      this.getList()      
    },         
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.showSureModal({
          "title":"删除提示",            
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认删除 "+item.id+" ?","callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    },    
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(){
      let firstDay = this.searchDate[0].Format('yyyy-MM-dd')
      let lastDay = this.searchDate[1].Format('yyyy-MM-dd')
      let date = [firstDay,lastDay]
      if(this.searchData.date=='NaN-aN-aN,NaN-aN-aN'){
        this.searchData.date=''
      }else {
          this.searchData.date = date.join(',')
      }
      this.onSearchGetList();
    },
    initDate(){     
      let beginDay,endDay= '';
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },       
    onSelectChange(label,value,reset){
      console.log(label,'onSelectChange');
      console.log(value,'onSelectChange');
    },    
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    //总计
    footerMethodFunc({ columns, data }){
      return [columns.map((item,index) => {
          if(index ==0){
            return '总计'
          }else if(['消耗积分'].includes(item.title)){
            return this.points_consume / 10000
          }else if(['账号消耗'].includes(item.title)){
            return this.points_consume_account / 10000
          }else if(['赠送消耗'].includes(item.title)){
            return this.points_consume_gift / 10000
          }else if(['利润'].includes(item.title)){
            return this.profit / 10000
          }else if(['任务数'].includes(item.title)){
            return this.task_nums
          }else if(['有效数'].includes(item.title)){
            return this.task_nums_valid
          }
          return null
        })
      ]
    },  
  },
  mounted() {
    bus.$on('update-recharge-account-list', this.initSearchData);// 更新充值账户列表
  },

  beforeDestroy() {
    bus.$off('update-recharge-account-list');
  },
};
</script>  